package test;

import java.util.LinkedList;
/*
* Snake表示蛇
*   一条蛇有6个节点
*     用集合存储起来
* */
public class snake {
   //蛇的身体
    private LinkedList<Node> body;
    private Direction direction = Direction.left;//设置运动方向默认为左边
    private boolean isliving = true;
    public snake() {
        //初始化蛇的身体
        initSnake();

    }
    //初始化蛇的身体
    private void initSnake() {
        body = new LinkedList<>();
        body.add(new Node(20,16));
        body.add(new Node(20,17));
        body.add(new Node(20,18));
//        body.add(new Node(20,19));
//        body.add(new Node(20,20));
//        body.add(new Node(20,21));
//        body.add(new Node(20,22));
//        body.add(new Node(20,23));
//        body.add(new Node(20,24));

    }

    //蛇沿着蛇头的方向移动
    public void move() {
           if (isliving){
               //获取蛇头
               Node head = body.getFirst();
               switch(direction) {
                   case up:
                       body.addFirst(new Node(head.getY()-1,head.getX()));
                       break;
                   case down:
                       body.addFirst(new Node(head.getY()+1,head.getX()));
                       break;
                   case left:
                       body.addFirst(new Node(head.getY(),head.getX()-1));
                       break;
                   case right:
                       body.addFirst(new Node(head.getY(),head.getX()+1));
                       break;
               }
               //删除最后一个节点
               body.removeLast();

               //判断蛇是否撞墙
               head = body.getFirst();
               if (head.getX()<0||head.getX()>=40||head.getY()>=40){
                   isliving = false;
               }
               //判断蛇是否碰到自己的身体
               for (int i = 1; i < body.size(); i++) {
                   Node node = body.get(i);
                   if (head.getX()==node.getX()&&head.getY()==node.getY()){
                       isliving = false;
                   }
               }

           }

    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public void eat(Node food) {
        Node head = body.getFirst();
        switch(direction) {
            case up:
                body.addFirst(new Node(head.getY()-1,head.getX()));
                break;
            case down:
                body.addFirst(new Node(head.getY()+1,head.getX()));
                break;
            case left:
                body.addFirst(new Node(head.getY(),head.getX()-1));
                break;
            case right:
                body.addFirst(new Node(head.getY(),head.getX()+1));
                break;
        }
    }
}
